/* 理财直融信息维护
 * zhanghaitao
 */
import React from 'react';
import { connect } from 'dva';
import { ContentPackage, DATA_ENTRY, AdvancedSearch, PrimaryC, TableC } from '../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import config from '../../../comps/business/searchAndSelect/enum';
import BasicInfo from './basicInfo';
import TransitionData from './transitionData';
@Form.create()
class MoneyInformation extends React.Component {
  state = {
    pageStatus: 1, // 页面状态 1-列表页  2-表单页
    currentPage: 1, // 当前页码
    numInPage: 10, // 一页数量
    total: 0, // 数据总数
    isReset: false, // 标记是否点击了“重置”后未重新查询
    columns: [
      { dataIndex: 'secucode', title: '证券代码', key: 'secucode', width: 180 },
      { dataIndex: 'secuabbr', title: '证券简称', key: 'secuabbr', width: 180 },
      { dataIndex: 'term', title: '期限', key: 'term', width: 90 },
      { dataIndex: 'interestDate', title: '起息日', key: 'interestDate', width: 120 },
      { dataIndex: 'cashDueDate', title: '到期日', key: 'cashDueDate', width: 150 },
      { dataIndex: 'actualTotal', title: '实际发行规模（万元）', key: 'actualTotal', width: 150 },
      { dataIndex: 'couponRate', title: '票面利率', key: 'couponRate', width: 100 },
      { dataIndex: 'financeName', title: '融资人', key: 'financeName', width: 180 },
    ],
    dataSource: [], // 表格数据
    // queryItem: '',           // 查询条件
    init: {}, // 表单回填数据
    inits: {}, // 转换后表单数据根据证券代码回填
    type: -1, // 类型
    isTransition: false, // 是否是转换
    isLoading: false,
    id: '',
    searchObj: {},
    sortedInfo: null, //排序对象
  };

  //初始化函数
  componentDidMount() {
    this.getList();
  }

  //获取表格数据
  getList = () => {
    const { currentPage, numInPage, searchObj, sortedInfo } = this.state;
    let obj = {};
    if (sortedInfo?.order) {
      (obj.columnKey = sortedInfo?.columnKey), (obj.order = sortedInfo?.order);
    }
    this.props.dispatch({
      type: 'moneyInformationM/queryMoneyInformation',
      payload: {
        ...searchObj,
        current: currentPage,
        pageSize: numInPage,
        ...obj,
      },
      callback: (data) => {
        if (data && JSON.stringify(data) != '{}') {
          this.setState({
            dataSource: data.dataSource,
            currentPage: data.pageInfo.currentPage,
            numInPage: data.pageInfo.numInPage,
            total: data.pageInfo.total,
          });
        } else {
          this.setState({
            dataSource: [],
            currentPage: 1,
            numInPage: 10,
            total: 0,
          });
        }
      },
    });
  };

  // 改变columns
  changecolumns = (columns) => {
    let { sortedInfo } = this.state;
    sortedInfo = sortedInfo || {};
    if (columns && columns.length) {
      if (columns[columns.length - 1].title != '操作') {
        columns.push({
          title: '操作',
          dataIndex: 'operate',
          key: 'operate',
          type: 'operate',
          width: 150,
          operates: [
            {
              title: '编辑',
              onClick: (record, index) => {
                this.onOkAccount(record.id);
              },
            },
            {
              title: '转换',
              onClick: (record, index) => {
                this.transitionAccount(record.id);
              },
            },
            {
              title: '删除',
              onClick: (record, index) => {
                this.deleteAccount(record.id);
              },
            },
          ],
        });
      }
      if (columns.length) {
        columns.map((item, index) => {
          if (item.key == 'secucode' || item.key == 'interestDate' || item.key == 'cashDueDate') {
            item.sorter = true;
            item.sortOrder = sortedInfo.columnKey === item.key && sortedInfo.order;
          }
          if (item.key == 'interestDate' || item.key == 'cashDueDate') {
            item.type = 'date';
          } else if (item.key == 'term') {
            item.render = (text, record) => {
              if (record.term) {
                if (record.company == 'Y') {
                  return record.term + '年';
                } else if (record.company == 'M') {
                  return record.term + '月';
                } else if (record.company == 'D') {
                  return record.term + '日';
                } else {
                  return record.term;
                }
              } else {
                return '--';
              }
            };
          } else if (item.key == 'couponRate') {
            item.align = 'right';
            item.render = (text, record, index) => {
              if (text === null || text === undefined) {
                return '--';
              } else {
                return Number(text).toFixed(2) + '%';
              }
            };
          } else if (item.key == 'actualTotal') {
            item.type = 'money';
          }
        });
      }
    }

    return columns;
  };

  // 响应查询
  onQuery = (e) => {
    if (e && Object.keys(e).length == 1 && Object.keys(e)[0] == 'secuId') {
      //产品名称精准查询时清空其他查询条件
      this.state.RANGEDATE.reset();
      this.state.RANGEDATEEnd.reset();
    }
    let tempQuery = {};
    for (let k in e) {
      if (k == 'startDateStart' || k == 'startDateEnd' || k == 'endDateStart' || k == 'endDateEnd') {
        tempQuery[k] = e[k].format('YYYY-MM-DD');
      } else {
        tempQuery[k] = e[k];
      }
    }
    this.setState(
      {
        isReset: false,
        currentPage: 1,
        searchObj: tempQuery,
      },
      () => {
        this.getList();
      },
    );
  };

  // 响应重置
  onClear = () => {
    this.setState({
      searchObj: {},
      sortedInfo: null, //排序对象
      isReset: true,
    });
  };

  // 响应编辑
  onOkAccount = (id) => {
    this.props.dispatch({
      type: 'moneyInformationM/editInformationById',
      payload: {
        id: id,
      },
      callback: (data) => {
        if (data) {
          this.setState({
            init: data,
            type: 2,
            pageStatus: 2,
          });
        } else {
          this.setState({
            init: {},
          });
        }
      },
    });
  };

  // 响应转换
  transitionAccount = (id) => {
    this.props.dispatch({
      type: 'moneyInformationM/editInformationById',
      payload: {
        id: id,
      },
      callback: (data) => {
        if (data) {
          this.setState({
            init: data,
            pageStatus: 2,
            isTransition: true,
          });
        } else {
          this.setState({ init: {} });
        }
      },
    });
  };

  // 响应删除
  deleteAccount = (id) => {
    this.props.dispatch({
      type: 'moneyInformationM/deleteInformationById',
      payload: {
        id: id,
      },
      callback: (data) => {
        if (data) {
          this.getList();
        } else {
          message.info('该标的已被引用，若要删除，请删除引用，或转换该标的后再执行删除。');
        }
      },
    });
  };

  // 响应新增
  addModalOpen = () => {
    this.setState({ type: 1, pageStatus: 2 });
  };

  // 响应取消
  onCancel = () => {
    this.setState({
      pageStatus: 1,
      init: {},
      inits: {},
      isTransition: false,
    });
  };

  // 响应保存
  orderInstruction = () => {
    const { isTransition, type, init } = this.state;
    if (isTransition) {
      let formdata = this.transitionDataRef.getInfo();
      let formdata1 = this.transitionDataRef.getInfo('1');
      if (formdata1) {
        let exchangecode = formdata1.exchangeCode;
        let tradingcode = formdata1.secucode1;
        if (formdata.secucode == formdata1.secucode1 || formdata.secucode == tradingcode) {
          message.info('请选择不同的标的进行转换');
        } else {
          this.setState({ isLoading: true });
          this.props.dispatch({
            type: 'moneyInformationM/transitionInformation',
            payload: {
              beforSecucode: formdata.secucode,
              tradingcode: tradingcode,
              exchangecode: exchangecode,
            },
            callback: (data) => {
              if (data) {
                this.setState(
                  {
                    pageStatus: 1,
                    init: {},
                    inits: {},
                    isTransition: false,
                    isLoading: false,
                    baseBaseInfoChangeReport: {
                      // 发行价格
                      parTotalValue: undefined,
                      // 计息方式
                      interestMethod: undefined,
                      // 计息频率
                      interestRate: undefined,
                      // 计息基础
                      interestBasis: undefined,
                      // 起息日
                      startDate: undefined,
                      // 到期日
                      endDate: undefined,
                      // 票面利率
                      fixedRate: undefined,
                    },
                  },
                  () => this.getList(),
                );
              } else {
                this.setState({ isLoading: false });
              }
            },
          });
        }
      } else {
        message.info('请选择要转换的标的');
      }
    } else {
      let formdata = this.basicInfoRef.getInfo();
      if (formdata) {
        let redempArrs = this.basicInfoRef.redempsGetInfo();
        if (!redempArrs) return;
        let params = {
          ...formdata,
          id: init.id || '',
          creator: init.id ? init.creator : localStorage.getItem('antd-pro-userId'),
          updateby: localStorage.getItem('antd-pro-userId'),
          type: type == 1 ? 'add' : 'update',
          zgtzptNonstandarCashFlows: redempArrs,
        };
        this.setState({ isLoading: true });
        this.props.dispatch({
          type: 'moneyInformationM/addMoneyInformation',
          payload: params,
          callback: (data) => {
            if (data) {
              this.setState(
                {
                  pageStatus: 1,
                  init: {},
                  isLoading: false,
                },
                () => this.getList(),
              );
            } else {
              this.setState({ isLoading: false });
            }
          },
        });
      }
    }
  };

  // 证券代码改变响应
  secucodeChange = (e) => {
    if (e) {
      this.props.dispatch({
        type: 'moneyInformationM/editInformationById',
        payload: {
          id: e.secucode,
        },
        callback: (data) => {
          if (data) {
            this.setState(
              {
                inits: data,
              },
              () => {
                this.transitionDataRef.setInits(data);
              },
            );
          } else {
            this.setState({ inits: {} });
          }
        },
      });
    }
  };

  //表格页码排序改变调用
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        sortedInfo: sorter,
      },
      () => {
        if (this.state.isReset) {
          //判断是否点击了重置 点击页码不进行后台查询
          message.warning('查询条件已被重置，请重新查询。');
          return;
        }
        this.setState(
          {
            dataSource: [],
            currentPage: current,
            numInPage: pageSize,
          },
          () => {
            this.getList();
          },
        );
      },
    );
  };

  render() {
    const { columns, dataSource, currentPage, numInPage, total, pageStatus, init, inits, type, isTransition, isLoading } = this.state;
    const { form, loading } = this.props;
    const newsColumns = this.changecolumns(columns);
    const searchProps = {
      dataSource: [
        {
          dataIndex: ['secuId', 'search_LIKE_secucode'],
          title: '证券代码',
          type: DATA_ENTRY.SEARCHANDSELECTC,
          codeType: config.lczr,
        },
        {
          dataIndex: ['startDateStart', 'startDateEnd'],
          title: '起息日区间',
          type: DATA_ENTRY.RANGEDATE,
          initialValue: [null, null],
          onRef: (ref) => this.setState({ RANGEDATE: ref }),
          disableFuture: false,
          allowClear: true,
        },
        {
          dataIndex: ['endDateStart', 'endDateEnd'],
          title: '到期日区间',
          type: DATA_ENTRY.RANGEDATE,
          initialValue: [null, null],
          onRef: (ref) => this.setState({ RANGEDATEEnd: ref }),
          disableFuture: false,
          allowClear: true,
        },
      ],
      onQuery: (e) => {
        //点击查询按钮
        this.onQuery(e);
      },
      onClear: () => {
        //点击重置按钮
        this.onClear();
      },
    };
    return (
      <ContentPackage
        title='非标（理财直融）维护'
        contentHtml={
          <div>
            <div style={{ display: pageStatus == 1 ? 'block' : 'none' }}>
              <AdvancedSearch {...searchProps} />
              <div>
                <PrimaryC title='新增' style={{ margin: '10px 0 10px 0' }} onClick={this.addModalOpen} />
              </div>
              <div>
                <TableC
                  columns={[...newsColumns]}
                  loading={loading}
                  dataSource={dataSource}
                  current={currentPage}
                  pageSize={numInPage}
                  total={total}
                  selfScrollY={true}
                  rowKey='id'
                  pagination={true}
                  onChange={this.handleTableChange}
                />
              </div>
            </div>
            {/* 新增/编辑 */}
            {!isTransition && pageStatus == 2 && (
              <div>
                <BasicInfo
                  form={form}
                  init={init}
                  type={type}
                  loading={isLoading}
                  pageStatus={pageStatus}
                  onCancel={this.onCancel}
                  onSave={this.orderInstruction}
                  onRef={(ref) => (this.basicInfoRef = ref)}
                />
              </div>
            )}
            {/* 转换 */}
            {isTransition && (
              <div>
                <TransitionData
                  form={form}
                  init={init}
                  inits={inits}
                  loading={isLoading}
                  onCancel={this.onCancel}
                  onSave={this.orderInstruction}
                  secucodeChange={this.secucodeChange}
                  onRef={(ref) => (this.transitionDataRef = ref)}
                />
              </div>
            )}
          </div>
        }
      />
    );
  }
}

export default connect(({ moneyInformationM, loading }) => ({ moneyInformationM, loading: loading.effects['moneyInformationM/queryMoneyInformation'] }))(MoneyInformation);
